package com.bdqn.ch09.pojo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public final class RedisPool {
    private static String ADDR = "192.168.0.100";
    private static int PORT = 6379;
    private static String AUTH="foobared";
    private static int MAX_ACTIVE=1024;
    private static int MAX_IDLE=200;
    private static int MAX_WAIT = 1000;
    private static int TIMEOUT=1000;

    private static boolean TEST_ON_BORROW = true;
    private static JedisPool jedisPool = null;

    static{
        try{
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public synchronized static Jedis getJedis(){
        try {
            if (jedisPool != null){
                Jedis resource = jedisPool.getResource();
                return resource;
            }else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void returnResource(final Jedis jedis){
        if (jedis != null){
            jedisPool.returnResource(jedis);
        }
    }
}
